<?php
/**
 * Created by PhpStorm.
 * Author: DaXiong
 * Date: 2018/10/22
 * Time: 15:17
 */

namespace App\Http\Controllers;


use App\Jobs\PlayAnAward;
use App\Models\Activity;
use App\Models\Address;
use App\Models\Join;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class JoinController extends Controller
{
    /**
     * 获取活动参与人员信息 get
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function info()
    {
        $activity_id = (int)request('activity_id', 0);
        $limit = (int)request('limit', '');

        if ($limit) {
            $info = Join::where('activity_id', $activity_id)
                ->with(['user' => function ($query) {
                    $query->select('id', 'avatar')->get();
                }])
                ->orderBy('id', 'DESC')
                ->paginate($limit);
        } else {
            $info = Join::where('activity_id', $activity_id)
                ->with(['user' => function ($query) {
                    $query->select('id', 'avatar')->get();
                }])
                ->orderBy('id', 'DESC')
                ->paginate(10);
        }

        if ($info) {
            return $this->returnJson(0, '参与活动人员信息', $info);
        }
        return $this->returnJson(1, '该活动暂无参与人员');
    }

    /**
     * 参与活动中将名单
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function winner()
    {
        $activity_id = (int)request('activity_id', 0);
        $info = Join::where('activity_id', $activity_id)
            ->whereBetween('status', [1, 3])
            ->with(['user' => function ($query) {
                $query->select('id', 'avatar')->get();
            }])
            ->orderBy('id', 'DESC')
            ->get();
        return $this->returnJson(0, '', $info);
    }

    /**
     * 报名参加活动抽奖
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function add()
    {

        $data['user_id'] = auth()->guard('api')->id();
//        $data['user_id'] = (int)request('user_id','');
        $data['activity_id'] = (int)request('activity_id', '');
        $data['password'] = (string)request('password', '');
        //验证活动口令
        $activityData = Activity::where(['id'=>$data['activity_id'], 'status' => Activity::STATUS_1])
            ->withCount('join')->first();

        if (!$activityData) {
            return $this->returnJson(1, '活动信息不存在或已结束');
        }
        $activityArray = $activityData->makeVisible('password')->toArray();
        if ($data['password'] != $activityArray['password']) {
            return $this->returnJson(1, '口令错误');
        }

        $info = Join::where('activity_id', $data['activity_id'])
            ->where('user_id', $data['user_id'])
            ->first();

        if (empty($info)) {
            DB::beginTransaction();
            try {
                $activityInfo = Activity::where(['id' => $data['activity_id'], 'status' => Activity::STATUS_1])->get();
                if (!$activityInfo->isEmpty()) {
                    Activity::where(['id' => $data['activity_id'], 'status' => Activity::STATUS_1])->increment('user_num', 1);
                    $address = Address::where(['user_id'=>$data['user_id']])->first();
                    if($address){
                        $address = $address->toArray();
                        Join::create([
                            'activity_id' => $data['activity_id'],
                            'user_id' => $data['user_id'],
                            'name' => $address['name'],
                            'mobile' => $address['mobile'],
                            'address' => $address['address'],
                            'code' => $address['code'],
                        ]);
                    }else{
                        Join::create([
                            'activity_id' => $data['activity_id'],
                            'user_id' => $data['user_id']
                        ]);
                    }

                    if($activityArray['wintype'] === Activity::WINTYPE_1 and $activityArray['open_num'] > 0 and $activityArray['open_num'] - 1 == $activityArray['join_count']){
                        PlayAnAward::dispatch(Activity::find($data['activity_id']));
                    }
                    DB::commit();
                    return $this->returnJson(0, '活动报名成功');
                } else {
                    DB::commit();
                    return $this->returnJson(1, '该活动已结束');
                }
            } catch (\Exception $exception) {
                Log::error($exception);
                DB::rollback();//事务回滚
                return $this->returnJson(1, '系统繁忙');
            }
        }
        return $this->returnJson(1, '已成功参与活动');
    }

    /**
     * 中奖用户选择设置收货地址
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function setAddress(){
        $data['activity_id'] = (int)request('activity_id',0);
        $data['name'] = (string)request('name','');
        $data['mobile'] = request('mobile','');
        $data['address'] = (string)request('address','');
        $data['code'] = (int)request('code',0);
        $user_id= auth()->guard('api')->id();

        $update = Join::where(['activity_id'=>$data['activity_id'],'user_id'=>$user_id])->update($data);
        if($update){
            return $this->returnJson(0, '');
        }
        return $this->returnJson(1, 'error');
    }

}